<!--
 * @Description: 因子列表
 * @Author: qingyang
 * @Date: 2022-01-10 16:04:17
 * @LastEditors: qingyang
 * @LastEditTime: 2023-06-26 10:17:44
-->
<template>
  <div class="factor-list-container">
    <CPageTable @register="registerPage" v-model:searchForm="searchForm">
      <template #level="{ scope }">
        <CLink
          v-if="scope.row.nodePath && scope.row.nodePath.includes('/')"
          @click="goDetail(scope.row)"
          >{{ scope.row.nodePath }}</CLink
        >
        <span v-else>{{ empty(scope.row.nodePath) }}</span>
      </template>
      <template #type="{ scope }">
        {{ FlowTypesListMap[scope.row.dataType] }}
      </template>
      <template #stage="{ scope }">
        {{ ProcessStageMap[scope.row.lifeCycleStage] }}
      </template>
      <template #nodeNameSlot="{ scope: { row } }">
        <CTableColumn :main-text="row.nodeName" :sub-text="row.nodeCode" subTextHideIfEmpty />
      </template>
      <template #data="{ scope }">
        <span v-if="scope.row.dosage === 0 || scope.row.dosage || scope.row.unit == 'pcs'">
          {{ scope.row.quantity }}
          {{ scope.row.unit == 'pcs' ? scope.row.unit : `· ${scope.row.dosage + scope.row.unit}` }}
        </span>
        <span v-else>-</span>
      </template>
      <template #keyProperty="{ scope }">
        <span
          v-html="
            scope.row.keyProperty && scope.row.keyProperty.includes('OTHER:')
              ? scope.row.keyProperty.split(':')[1]
              : empty(scope.row.keyProperty)
          "
        ></span>
      </template>

      <template #factorValue="{ scope }">
        <span v-if="scope.row.relateStatus == RelateStatusEnum.IGNORE">{{
          RelateStatusMap.IGNORE
        }}</span>
        <!-- <span v-else-if="scope.row.relateStatus == RelateStatusEnum.SUPPLIER">{{
          RelateStatusMap.SUPPLIER
        }}</span> -->

        <!-- <el-button class="g-link" link @click="(e: Event) => handleClickTooltipDetail(e, scope.row)"
          ></el-button
        > -->
        <template v-else-if="scope.row.relateStatus == RelateStatusEnum.RELATE">
          <el-popover placement="bottom" :width="270">
            <template #reference>
              <div class="g-link"> {{ scope.row.factor }}{{ scope.row.factorUnit }} </div>
            </template>
            <div>
              <p class="g-font-12n2">因子名称: {{ empty(scope.row.factorName) }}</p>
              <p class="g-font-12n2">因子编号: {{ empty(scope.row.factorNo) }}</p>
              <p class="g-font-12n2">因子值: {{ empty(scope.row.factor) }}</p>
              <p class="g-font-12n2">因子单位: {{ empty(scope.row.factorUnit) }}</p>
              <p class="g-font-12n2"
                >因子来源: {{ empty(FactorSourceMap[scope.row.factorSource]) }}</p
              >
            </div>
          </el-popover>
        </template>
        <span v-else>-</span>
      </template>
      <template #op="{ scope }">
        <CTableButtonGroup :showMoreNum="1" :buttons-config="getTableButtonsConfig(scope.row)" />
      </template>
      <template #batchOperaBtns="{ selection }">
        <el-button
          v-btnPermission="'PCF_FACTOR_MATCH'"
          class="c-btn28"
          @click="handleBatchRelate(selection)"
          type="primary"
          :disabled="!(selection.length > 0)"
          >批量关联</el-button
        >
        <el-button
          v-btnPermission="'PCF_PROCESS_DATA_EDIT'"
          :loading="ignoreLoading"
          class="c-btn28"
          @click="handleBatchIgnore(selection)"
          type="primary"
          :disabled="!(selection.length > 0)"
          >批量忽略不可得</el-button
        >
      </template>
    </CPageTable>
    <LevelDetail
      v-model:visible="seeDetail"
      :flowName="flowName"
      :expandedKey="selectId"
    ></LevelDetail>
    <CFootprintFactorDrawer
      v-model:visible="relationVisible"
      :modelNo="modelNo"
      :nodeNoList="nodeNoList"
      @finish="refresh"
    ></CFootprintFactorDrawer>
  </div>
  <GDetailPopover v-model:visible="tooltipVisible" title="因子详情"> </GDetailPopover>
</template>
<script lang="ts">
export default {
  name: 'FactorList'
};
</script>
<script lang="ts" setup>
import { reactive, ref, inject, defineExpose } from 'vue';
import { CPageTable, useCPageTable, CPageTableProps } from '@/components/CPageTable';
import { useFactorList } from './useFactorList';
import { empty } from '@/utils/index';
import { useMessage } from '@/hooks/useMessage';
import { useRouter } from 'vue-router';
import { useKeepAliveRefresh } from '@/hooks/useKeepAliveRefresh';
import { IFlowListItem } from '@/apis/pcf/myModel/model/modelDetailModel';
import type { TableButtonItem } from '@/components/CTable';
import { CTableColumn, CTableButtonGroup } from '@/components/CTable';
import { CLink } from '@/components/CLink/index';
import LevelDetail from './LevelDetail.vue';
import CFootprintFactorDrawer from '@/businessComponents/CFootprintFactorDrawer/index.vue';
import { useGDetailPopover, GDetailPopover } from '@/components/GDetailPopover/index';
import {
  ProcessStageMap,
  FlowTypesListMap,
  RelateStatusEnum,
  RelateStatusMap,
  FlowNodeTypeEnum,
  FactorSourceMap
} from '@/constants/enum';
import { MODEL_DETAIL_ROOT } from '../../../../types';
import type { ModelDetailRootProvider } from '../../../../types';
import { updateIgnore, batchUpdateIgnore, batchIgnoreByData } from '@/apis/pcf/myModel/modelDetail';
const { modelNo } = inject(MODEL_DETAIL_ROOT) as ModelDetailRootProvider;
const { createConfirm, createMessage } = useMessage();
const router = useRouter();
const seeDetail = ref(false);
const flowName = ref('');
const selectId = ref('');
const relationVisible = ref(false);
const nodeNoList = ref<string[]>([]);
const { searchOptions, searchForm, tableOptions, tableFieldsSetting } = useFactorList(modelNo);
const options = reactive<CPageTableProps>({
  title: '',
  showPageHeader: false,
  searchOptions: searchOptions,
  tableOptions,
  tableFieldsSetting,
  enableFieldsSetting: true
});
const { tooltipVisible, tooltipRow, handleClickTooltipDetail } = useGDetailPopover();

function getTableButtonsConfig(row: IFlowListItem): TableButtonItem[] {
  let btnArr = [
    {
      text: row.relateStatus == RelateStatusEnum.RELATE ? '重新关联' : '关联因子',
      btnPermission: 'PCF_FACTOR_MATCH',
      onClick: () => handleRelation(row)
    }
  ];
  if (row.relateStatus !== 'IGNORE') {
    btnArr.push({
      text: '标注为忽略或不可得',
      btnPermission: 'PCF_PROCESS_DATA_EDIT',
      onClick: () => tagClick(row)
    });
  }
  return btnArr;
}

const [registerPage, { refresh, getSelection }] = useCPageTable(options);

const tagClick = async (row: IFlowListItem) => {
  await updateIgnore(row.nodeNo);
  createMessage.success('标记为忽略不可得成功！');
  refresh();
};
const goDetail = (row: IFlowListItem) => {
  flowName.value = row.nodeName;
  selectId.value = row.nodeNo;
  seeDetail.value = true;
};

// 关联因子库
function handleRelation(row: IFlowListItem) {
  // 关联因子库时的nodeNo为当前行的nodeNo
  nodeNoList.value = [row.nodeNo];
  // 获取当前节点的关联因子
  relationVisible.value = true;
}
function handleBatchRelate(selection: any) {
  const nodeNoListArr: string[] = selection.map((item: any) => item.nodeNo);
  nodeNoList.value = nodeNoListArr;
  // 获取当前节点的关联因子
  relationVisible.value = true;
}
const handleBatch = () => {
  if (getSelection().length > 0) {
    handleBatchRelate(getSelection());
  } else {
    createMessage.warning('请先选择需要关联因子的数据');
  }
};

const ignoreLoading = ref(false);
async function handleBatchIgnore(selection: any[]) {
  const nodeNoListArr: string[] = selection.map((item: any) => item.nodeNo);
  ignoreLoading.value = true;
  try {
    await batchUpdateIgnore(nodeNoListArr);
    createMessage.success('标记为忽略不可得成功！');
    refresh();
  } finally {
    ignoreLoading.value = false;
  }
}

/**
 * 批量忽略<0.01g记录
 */
async function batchIgnoreByDataFn() {
  try {
    ignoreLoading.value = true;
    await batchIgnoreByData(modelNo);
    createMessage.success('批量忽略<0.01g记录成功！');
    ignoreLoading.value = false;
    refresh();
  } catch (error) {
    ignoreLoading.value = false;
    console.log('error', error);
  }
}

const batchIgnore = () => {
  if (getSelection().length > 0) {
    handleBatchIgnore(getSelection());
  } else {
    createMessage.warning('请先选择需要忽略不可得的数据');
  }
};

defineExpose({
  handleBatch,
  batchIgnore,
  batchIgnoreByDataFn,
  refresh,
  ignoreLoading
});
useKeepAliveRefresh(refresh);
</script>

<style lang="scss" scoped>
.my-model-list-container {
  min-height: 80%;
}
.factor-list-container {
  :deep(.c-page-table__body) {
    margin: 0;
  }
  :deep(.body-main__filter) {
    padding-top: 16px;
  }
}
</style>
